exports.install = install;

function install(socket) {
	const Admin = tableMap.get("admin");
	socket.HTTPContext.prototype.admin_loginer = function(ignore_error) {
		const loginer_admin_id = this.session.loginer_admin_id;
		if (!loginer_admin_id && !ignore_error) {
			Throw("ref", "管理员未登录");
		}
		return Admin.findOne({
			_id: ["ObjectID", "@", loginer_admin_id]
		});
	};
	return {
		prefix: "/admin",
		get: {
			"/loginer": [{
				des: "获取已经登录的管理员",
				emit_with: ["session"]
			}, function*() {
				this.body = yield this.admin_loginer();
			}]
		},
		post: {
			"/login": [{
				des: "管理员登录",
				doc: {
					params: [{
						name: "admin_name",
						type: "<form>string",
					}, {
						name: "admin_pwd",
						type: "<form>string",
					}]
				},
				emit_with: ["session", "form"]
			}, function*() {
				const admin_name = this.form.admin_name;
				if (!admin_name) {
					Throw("请输入管理员帐号")
				}
				const admin_pwd = this.form.admin_pwd;
				if (!admin_pwd) {
					Throw("请输入管理员密码")
				}
				const admin = yield tableMap.get("admin").findOne({
					admin_name: admin_name,
				});
				if (!admin) {
					Throw("ref", "找不到指定管理员帐号")
				}
				if (admin.admin_pwd !== $$.md5_2(admin_pwd)) {
					Throw("管理员密码有误")
				}
				this.session.loginer_admin_id = admin._id;
				this.body = admin;
			}],
			"/create": [{
				des: "创建管理员",
				doc: {
					params: [{
						name: "admin_name",
						type: "<form>string",
					}, {
						name: "admin_pwd",
						type: "<form>string",
					}]
				},
				emit_with: ["session", "form"]
			}, function*() {
				const admin_name = this.form.admin_name;
				if (!admin_name) {
					Throw("请输入管理员帐号")
				}
				const admin_pwd = this.form.admin_pwd;
				if (!admin_pwd) {
					Throw("请输入管理员密码")
				}
				const Admin = tableMap.get("admin")
				if (yield Admin.findOne({
						admin_name: admin_name,
					})) {
					Throw("管理员帐号已经存在，无法重复创建")
				}
				const admin = yield Admin.insertOne({
					admin_name: admin_name,
					admin_pwd: $$.md5_2(admin_pwd)
				});
				this.body = admin;
			}]
		},
		delete: {
			"/loginout": [{
				des: "管理员退出登录",
				emit_with: ["session"]
			}, function() {
				this.session.loginer_admin_id = null;
				this.body = Date.now();
			}]
		}
	};
};